package com.fable.biz.operate.impl;

import com.fable.biz.operate.ContactsService;
import com.fable.dal.condition.ContactsQueryCondition;
import com.fable.dal.dto.ContactsDTO;
import com.fable.dal.mapper.ContactsMapper;
import com.fable.dal.mapper.ext.ContactsExtMapper;
import com.fable.dal.model.ContactsDO;
import com.fable.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName ContactsServiceImpl
 * @Description TODO
 * @Author aaters
 * @Date 2018/8/12 下午1:48
 * @Version 1.0
 **/
@Service("contactsService")
public class ContactsServiceImpl implements ContactsService {

    private static final Logger LOG = LoggerFactory.getLogger(CustomerServiceImpl.class);

    @Autowired
    private ContactsExtMapper mapper;

    @Autowired
    private ContactsMapper contactsMapper;

    @Override
    public List<ContactsDTO> findContactsAll(ContactsQueryCondition condition) {
        List<ContactsDTO> list = new ArrayList<>();
        try {
            if (StringUtil.isNotBlank(condition.getGmtStartTime())) {
                String startTime = condition.getGmtStartTime() + " 00:00:00";
                condition.setGmtStartTime(startTime);
            }
            if (StringUtil.isNotBlank(condition.getGetEndTime())) {
                String endTime = condition.getGetEndTime() + " 23:59:59";
                condition.setGetEndTime(endTime);
            }
            list = mapper.findByContacts(condition);
            LOG.info("获取客户计划成功:{}", list);
            return list;
        } catch (Exception e) {
            LOG.info("获取客户计划失败:{}", list);
            return list;
        }
    }

    @Override
    public int delContacts(ContactsDO contactsDO) {
        int count = 0;
        try {
            count = contactsMapper.updateByPrimaryKeySelective(contactsDO);
            LOG.info("逻辑删除客户小计成功:" + count);
        } catch (Exception e) {
            LOG.error("逻辑删除客户小计失败:{}", e.getLocalizedMessage());
        }
        return count;
    }

    @Override
    public ContactsDO findContactsById(Integer id) {
        return contactsMapper.selectByPrimaryKey(id);
    }

    @Override
    public int addOrModifyContacts(ContactsDO contactsDO) {
        int count = 0;
        try {
            if (contactsDO.getId() != null) {
                contactsDO.setGmtModified(new Date());
                count = contactsMapper.updateByPrimaryKeySelective(contactsDO);
            } else {
                contactsDO.setGmtCreate(new Date());
                contactsDO.setGmtModified(new Date());
                count = contactsMapper.insertSelective(contactsDO);
            }
            LOG.info("添加或修改客户小计成功:");
        } catch (Exception e) {
            LOG.info("添加或修改客户小计失败:", e);
        }
        return count;
    }
}
